#!/bin/bash
################################################################################
# Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The OpenAirInterface Software Alliance licenses this file to You under 
# the Apache License, Version 2.0  (the "License"); you may not use this file
# except in compliance with the License.  
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------
# For more information about the OpenAirInterface (OAI) Software Alliance:
#      contact@openairinterface.org
################################################################################

# file run_mme
# brief run script for MME.
# author  Lionel GAUTHIER
# company Eurecom
# email:  lionel.gauthier@eurecom.fr 


################################
# include helper functions
################################
THIS_SCRIPT_PATH=$(dirname $(readlink -f $0))
source $THIS_SCRIPT_PATH/../build/tools/build_helper
declare -i g_run_msc_gen=0
declare    g_msc_dir="/tmp"
declare    g_mme_default_config_file="/usr/local/etc/oai/mme.conf"
declare    g_mme_default_fqdn=`hostname`".openair4G.eur"

set_openair_env 


function help()
{
  echo_error " "
  echo_error "Usage: run_mme [OPTION]..."
  echo_error "Run the MME executable."
  echo_error " "
  echo_error "Options:"
  echo_error "Mandatory arguments to long options are mandatory for short options too."
  echo_error "  -c, --config-file     file_abs_path Config file to be used by MME if you don't want to use the default one: $g_mme_default_config_file"
  echo_error "  -D, --daemon                        Run the daemon."
  echo_error "  -g, --gdb                           Run with GDB."
  echo_error "  -G, --gdb-cmd         cmd cmd_arg   Append this GDB cmd to GDB command file (ex1: break Attach.c:272, ex2: watch 0xffee0002)."
  echo_error "                                      All repetitions of this argument are valid."
  echo_error "  -h, --help                          Print this help."
  echo_error "  -I, --install-mme-files             Install MME config files. (NOT RECOMMENDED. See tutorials on https://gitlab.eurecom.fr/oai/openairinterface5g/wikis/OpenAirUsage or docs/EPC_User_Guide.pdf"
  echo_error "  -k, --kill                          Kill all running MME instances, exit script then."
  echo_error "  -m, --mscgen          directory     Generate mscgen output files in a directory"
  echo_error "  -v, --verbosity-level               Verbosity level (0,1,2)."
  echo_error "                                        0 -> ASN1 XER printf off"
  echo_error "                                        1 -> ASN1 XER printf on and ASN1 debug off"
  echo_error "                                        2 -> ASN1 XER printf on and ASN1 debug on"
}

function do_msc_gen()
{
  cd $g_msc_dir
  $THIS_SCRIPT_PATH/msc_gen
}

function control_c()
# run if user hits control-c
{
  echo_warning "\nExiting by ctrl+c\n"
  if [ $g_run_msc_gen -eq 1 ]; then 
    do_msc_gen
  fi
  exit $?
}

NAME=mmed
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS=""
PIDFILE=/var/run/$NAME.pid
function main()
{
  local -i run_gdb=0
  local -i run_daemon=0
  local -i set_network_interfaces=0
  local -i var_check_install_mme_files=0
  local    exe_arguments=" "
  local    mme_config_file=$g_mme_default_config_file
  local -a gdb_args
  local -i gdb_index=0

  until [ -z "$1" ]
    do
    case "$1" in
      -c | --config-file)
        mme_config_file=$2
        echo "setting config file to: $mme_config_file"
        shift 2;
        ;;
      -D | --daemon)
        run_daemon=1
        echo "Run MME as a daemon"
        shift;
        ;;
      -g | --gdb)
        run_gdb=1
        echo "setting GDB flag to: $run_gdb"
        shift;
        ;;
      -G | --gdb-arg)
        run_gdb=1
        gdb_args[$gdb_index]="$2 $3"
        echo "Appending gdb args: ${gdb_args[$gdb_index]}"
        gdb_index=$((gdb_index + 1))
        shift 3;
        ;;
      -h | --help)
        help
        exit 0
        ;;
      -i | --set-nw-interfaces)
        set_network_interfaces=1
        echo "setting network interfaces: $set_network_interfaces"
        shift;
        ;;
      -I | --install-mme-files)
        echo "Install MME files: .conf files."
        var_check_install_mme_files=1
        shift;
        ;;
      -k | --kill)
        $SUDO killall -q mme
        $SUDO rm /var/run/mme.pid
        do_stop_daemon
        exit 0
        shift;
        ;;
      -m | --mscgen)
        g_msc_dir=$2
        if [ -d  "$g_msc_dir" ]; then
          echo "setting mscgen log files to dir: $g_msc_dir"
          g_run_msc_gen=1
          shift 2;
        else
          echo_error "Mscgen log dir does not exist"
          exit -1
        fi
        ;;          
      -v | --verbosity-level)
        local verbosity_level=$2
        echo "setting verbosity level to: $verbosity_level"
        exe_arguments="-v $verbosity_level $exe_arguments"
        shift 2;
        ;;
      *)   
        echo "Unknown option $1"
        help
        exit 0
        ;;
    esac
  done

  set_openair_env 
  cecho "OPENAIRCN_DIR    = $OPENAIRCN_DIR" $green

  #####################################
  # Install config files
  #####################################
  if [ ! -f $mme_config_file ]; then 
    if [ $g_mme_default_config_file != $mme_config_file ]; then
      echo_fatal "Please provide -c|--config-file valid argument (\"$mme_config_file\" not a valid file)"
    fi
  fi
  
  if [ $var_check_install_mme_files -gt 0 ];then
    $SUDO mkdir -p /usr/local/etc/oai/freeDiameter > /dev/null
  
    if [ ! -f /usr/local/etc/oai/mme.conf ]; then
      $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/mme.conf    /usr/local/etc/oai
      echo_fatal "Please customize /usr/local/etc/oai/mme.conf (interfaces, TAIs, GUMMEI, HSS hostname, SGW IP address, logging, etc), after, please re-run run_mme -I"
    else
      if [  $THIS_SCRIPT_PATH/../etc/mme.conf -nt  /usr/local/etc/oai/mme.conf ]; then
        read -p "Do you want to update /usr/local/etc/oai/mme.conf with $OPENAIRCN_DIR/etc/mme.conf ? <y/N> " prompt
        if [[ $prompt =~ [yY](es)* ]]; then
          $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/mme.conf    /usr/local/etc/oai
          echo_fatal "Please customize /usr/local/etc/oai/mme.conf (interfaces, TAIs, GUMMEI, HSS hostname, SGW IP address, logging, etc), after, please re-run run_mme -I"
        fi
      fi
    fi 
  
    $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/mme_fd.conf /usr/local/etc/oai/freeDiameter
    echo_warning "Be carefull /usr/local/etc/oai/freeDiameter/mme_fd.conf has realm, freeDiameter identity, HSS "
    echo_warning "IPv4 address, HSS realm, HSS FQDN, all hardcoded, please check them and change them upon your needs."
  
    # hardcoded MME diameter ID 
    fqdn=`hostname --fqdn`
    if [ "a$fqdn" == "a" ]; then
      echo_error "Please allow the IP resolution of MME FQDN (in /etc/hosts, example: 127.0.1.1 myhostname.openair4G.eur myhostname)."
      echo_fatal "Please allow the IP resolution of HSS FQDN (in /etc/hosts, example: 127.0.1.1 hss.openair4G.eur hss if HSS run on MME host)."
    fi

    # generate certificates if necessary
    echo_warning "Generating MME certificates using MME FQDN $fqdn, if you want to use an other"
    echo_warning "FQDN, please modify mme_fd.conf, /etc/hosts consistently and then "
    echo_warning "re-run $OPENAIRCN_DIR/scripts/check_mme_s6a_certificate /usr/local/etc/oai/freeDiameter $fqdn consistently"
    $SUDO $OPENAIRCN_DIR/scripts/check_mme_s6a_certificate /usr/local/etc/oai/freeDiameter $fqdn
  fi

  #####################################
  # Check executables
  #####################################
  if [ "$run_daemon" -eq 1 ]; then
    if [ ! -e /usr/sbin/mmed ]; then
      echo_fatal "Cannot find /usr/sbin/mmed executable, have a look at the output of build_mme  -D ... executable"
    fi
  else
    if [ ! -e /usr/local/bin/mme ]; then
    echo_fatal "Cannot find /usr/local/bin/mme executable, have a look at the output of build_mme executable"
    fi
  fi


  #####################################
  # Clean old MSC generated files
  #####################################
  if [ $g_run_msc_gen -eq 1 ]; then 
    $SUDO rm -f /tmp/openair.msc.*
  fi

  if [ $set_network_interfaces -eq 1 ]; then
    set_mme_network_interfaces $mme_config_file
  fi
    
  #####################################
  # Running daemon?
  #####################################
  DAEMON_ARGS=$DAEMON_ARGS" -c $mme_config_file"
  if [ "$run_daemon" -eq 1 ]; then
    # TODO options
    $SUDO killall -q mme
    do_stop_daemon
    case "$?" in
      0) echo_success "MME daemon was running -> stopped";;
      1) ;;
      2) echo_fatal "FAILURE: MME daemon was running -> could not stop it";;
    esac
    do_start_daemon
    case "$?" in
      0) echo_success "MME daemon started";;
      1) echo_fatal "FAILURE: MME daemon was already running";;
      2) echo_fatal "FAILURE: Cannot start MME daemon";;
    esac
    exit 0
  fi

  #####################################
  # Running executable
  #####################################
  exe_arguments="-c $mme_config_file $exe_arguments"

  if [ $run_gdb -eq 0 ]; then 
    # trap keyboard interrupt (control-c)
    trap control_c SIGINT
    $SUDO mme  `echo $exe_arguments` 2>&1 
  else
    # trap keyboard interrupt (control-c) is done by gdb
    $SUDO touch      ~/.gdb_mme
    $SUDO chmod 777  ~/.gdb_mme
    $SUDO echo "file mme" > ~/.gdb_mme
    $SUDO echo "set args $exe_arguments "        >> ~/.gdb_mme
    for i in `seq 0 $gdb_index`; do
      $SUDO echo "${gdb_args[$i]}"               >> ~/.gdb_mme
    done
    $SUDO echo "run"                             >> ~/.gdb_mme
    $SUDO cat ~/.gdb_mme
    $SUDO gdb -n -x ~/.gdb_mme
    if [ $g_run_msc_gen -eq 1 ]; then 
      #$SUDO do_msc_gen
      cd $g_msc_dir
      $SUDO $THIS_SCRIPT_PATH/msc_gen --profile MME --dir $g_msc_dir --type png
    fi
  fi
}

main "$@"
